package com.niit.drugsmanager.controller;

import com.niit.drugsmanager.entity.Notice;
import com.niit.drugsmanager.entity.NoticeStatus;
import com.niit.drugsmanager.entity.User;
import com.niit.drugsmanager.service.NoticeService;
import com.niit.drugsmanager.service.NoticeStatusService;
import com.niit.drugsmanager.service.UserService;
import com.niit.drugsmanager.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/notices")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeStatusService noticeStatusService;

    @GetMapping
    public String getAllNotices(
            Model model,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0011);
        boolean flag2 = user.hasPermission(0b0100);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";
        if(!user.hasRole(0b0001)) return "redirect:/api/user/ban";

        model.addAttribute("notices", noticeService.getAllNotice());
        Map<Long, Boolean> statusMap = noticeStatusService.getNoticeStatusByUserId(user.getId())
                .stream().collect(Collectors.toMap(
                        NoticeStatus::getNid,
                        noticeStatus -> true)
                );
        model.addAttribute("noticeStatus", statusMap);
        return "notice/index";
    }

    @PostMapping("/new")
    public String showCreateForm(
            Model model,
            HttpSession session) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0101);
        boolean flag2 = user.hasPermission(0b0100);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

        model.addAttribute("notice", new Notice());
        return "notice/form";
    }

    @PostMapping("/edit")
    public String showEditForm(
            @RequestParam("nid") Long nid,
            Model model,
            HttpSession session) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0101);
        boolean flag2 = user.hasPermission(0b0100);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

        Notice notice = noticeService.getNoticeById(nid);
        if(notice != null) {
            model.addAttribute("notice", notice);
        }
        return "notice/form";
    }

    @PostMapping("/save")
    public String saveNotice(
            @ModelAttribute("notice") Notice notice,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        try {
            //登录检查
            User user = (User) session.getAttribute("user");
            String s = SessionUtils.ifUserNull(user, userService);
            if(s != null) return s;

            //权限检查
            boolean flag1 = user.hasRole(0b0101);
            boolean flag2 = user.hasPermission(0b0100);
            if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

            if (notice.getId() == null) {
                notice.setCreateTime(LocalDateTime.now());
                noticeService.saveNotice(notice);
                redirectAttributes.addFlashAttribute("successMessage", "通知创建成功");
            } else {
                noticeService.saveNotice(notice);
                redirectAttributes.addFlashAttribute("successMessage", "通知更新成功");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败: " + e.getMessage());
        }
        return "redirect:/api/notices";
    }

    @PostMapping("/delete")
    public String deleteNotice(
            @RequestParam("nid") Long nid,
            RedirectAttributes redirectAttributes,
            HttpSession session) {
        try {
            //登录检查
            User user = (User) session.getAttribute("user");
            String s = SessionUtils.ifUserNull(user, userService);
            if(s != null) return s;

            //权限检查
            boolean flag1 = user.hasRole(0b0101);
            boolean flag2 = user.hasPermission(0b0100);
            if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

            noticeStatusService.deleteNoticeStatusByNid(nid);
            noticeService.deleteNotice(nid);
            redirectAttributes.addFlashAttribute("successMessage", "通知删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败: " + e.getMessage());
        }
        return "redirect:/api/notices";
    }

    @PostMapping("/markRead")
    public String markRead(
            @RequestParam("nid") Long nid,
            RedirectAttributes redirectAttributes,
            HttpSession session){
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0011);
        boolean flag2 = user.hasPermission(0b0100);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

        NoticeStatus noticeStatus = new NoticeStatus();
        noticeStatus.setNid(nid);
        noticeStatus.setUid(user.getId());
        noticeStatus.setReadTime(LocalDateTime.now());
        noticeStatusService.addNoticeStatus(noticeStatus);
        return "redirect:/api/notices";
    }

    @PostMapping("/detail")
    public String getNoticeDetails(
            @RequestParam("nid") Long nid,
            Model model,
            HttpSession session) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b0011);
        boolean flag2 = user.hasPermission(0b0100);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

        Notice notice = noticeService.getNoticeById(nid);
        model.addAttribute("notice", notice);
        return "notice/detail";
    }
}
